package com.androidnetframe.exception;

import android.graphics.Color;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.widget.RelativeLayout.LayoutParams;

import com.androidnetframe.BaseParentActivity;
import com.androidnetframe.httputil.BaseRequestFilterLayer;
import com.androidnetframe.utils.LogcatHelper;

/**
 * @author 何强
 *         2015-9-22
 *         作用：展示View到具体的Activity上去
 */
public class MypreDrawListener implements OnPreDrawListener {

    public boolean isTransparence;
    public ViewGroup rootView;
    public CodeTypeObject codeTypeObject;
    public BaseRequestFilterLayer filter;
    LayoutParams params;
    public BaseParentActivity activity;

    public MypreDrawListener(final ViewGroup rootView, final boolean isTransparence, final CodeTypeObject codeTypeObject, final BaseRequestFilterLayer filter, BaseParentActivity activity) {

        init(rootView, isTransparence, codeTypeObject, filter, activity);
    }

    @Override
    public boolean onPreDraw() {
        rootView.getViewTreeObserver().removeOnPreDrawListener(this);

		/*显示错误页面*/
        showOverideView(rootView, isTransparence, codeTypeObject, filter);
		/*禁用加载布局的透点效果*/
		 /*避免在点击错误布局的时候，还能透点下面的控件*/
        codeTypeObject.view.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
		/*实现刷新按钮*/
        BaseParentActivity.OverideParams params = activity.filterRootView_errorView.get(filter.hashCode()+filter.getClass().getName());
        if (params != null) {//如果没有标记起始位置的情况，就会导致params==null
            if (params.errorState && codeTypeObject.haveRefreshButton) {//如果有刷新按钮，那么就添加刷新行为
                refresh(filter);
            }
        }
        return false;
    }

    public void init(final ViewGroup rootView, final boolean errorType, final CodeTypeObject codeTypeObject, final BaseRequestFilterLayer filter, BaseParentActivity activity) {
        this.rootView = rootView;
        this.isTransparence = errorType;
        this.codeTypeObject = codeTypeObject;
        this.filter = filter;
        this.activity = activity;
        params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    }

    public void showOverideView(ViewGroup rootView, boolean isTransparence, CodeTypeObject codeTypeObject, BaseRequestFilterLayer filter) {
		/*如果错误页面已经展示了，就直接返回*/
        if (filter.requestDone) {//如果网络请求的回调已经先于本方法执行完了，那么就没有必要再往下执行了
            return;
        }

        BaseParentActivity.OverideParams tempOverideParams = activity.filterRootView_errorView.get(filter.hashCode()+filter.getClass().getName());
        if (tempOverideParams != null) {
            if (!codeTypeObject.shortShowView && tempOverideParams.errorState) {//其他类型的错误布局
                return;
            } else if (codeTypeObject.shortShowView && tempOverideParams.loadingViewState) {//如果loadding已经显示了，那么就不应该再显示
                return;
            }
        }

        String[] idChar = getIdChar();
        if (idChar == null) {//如果没有标记符号,那么就直接返回
            return;
        }

        //是否是内置符号-没有起点也没有结束点
        if (idChar[0].equals(OverideLayout.No_Start) && idChar[1].equals(OverideLayout.No_End)) {
            //直接添加传递进来的View
            codeTypeObject.view.setLayoutParams(params);
            if (codeTypeObject.shortShowView && isTransparence) {
                codeTypeObject.view.setBackgroundColor(Color.TRANSPARENT);
            }
            recordOverideParamsInfo(tempOverideParams);
            return;
        }

        int topId = activity.getResources().getIdentifier(idChar[0], "id", activity.getPackageName());
        int bottomId = activity.getResources().getIdentifier(idChar[1], "id", activity.getPackageName());

        int overideHeight = -1;
        int topLocation[] = null;
        int topHeight = -1;
        View topView = null;
        if (topId == 0) {
            //如果没有取到顶部id，直接返回
            return;
        } else {//如果只有顶部id，看尾部id是否是内置标识符
            topLocation = getLocationOnScreen(topId);
            topView = rootView.findViewById(topId);
            if (topView == null) {
                return;
            }
            topHeight = topView.getMeasuredHeight();
            if (idChar[1].equals(OverideLayout.No_End)) {

                int[] rootLocation = new int[2];
                rootView.getLocationOnScreen(rootLocation);
                int rootHeight = rootView.getMeasuredHeight();
                //确定将要展示View的高度
                overideHeight = (rootHeight + rootLocation[1]) - (topLocation[1] + topHeight);
					
					/*重置覆盖布局的参数*/
                params.height = overideHeight;
                params.topMargin = topView.getTop() + topHeight;
                codeTypeObject.view.setLayoutParams(params);
                //如果是Loadidng类型的布局，可以将它的背景设置为透明
                if (codeTypeObject.shortShowView && isTransparence) {
                    codeTypeObject.view.setBackgroundColor(Color.TRANSPARENT);
                }
                //记录当前filter对应的ViewGroup和errorView以及其他一些细节
                recordOverideParamsInfo(tempOverideParams);
                return;
            }
        }

        if (bottomId == 0) {//如果没有取到底部id，直接返回
            return;
        } else {
            int[] bottomLocation = getLocationOnScreen(bottomId);
            if (bottomLocation == null) {
                return;
            }
            overideHeight = (bottomLocation[1]) - (topLocation[1] + topHeight);
        }
			
			/*重置覆盖布局的参数*/
        params.height = overideHeight;
        params.topMargin = topView.getTop() + topHeight;
        codeTypeObject.view.setLayoutParams(params);
        //如果是Loadidng类型的布局，可以将它的背景设置为透明
        if (codeTypeObject.shortShowView && isTransparence) {
            codeTypeObject.view.setBackgroundColor(Color.TRANSPARENT);
        }
        //记录当前filter对应的ViewGroup和errorView以及其他一些细节
        recordOverideParamsInfo(tempOverideParams);

    }

    public void recordOverideParamsInfo(BaseParentActivity.OverideParams overideParams) {
        BaseParentActivity.OverideParams tempOverideParams = overideParams;
        if (tempOverideParams == null) {
            tempOverideParams = activity.new OverideParams();
        }
        tempOverideParams.filter = filter;
        tempOverideParams.rootView = rootView;
        if (codeTypeObject.shortShowView) {//添加loadding框
            tempOverideParams.addLoadingView(codeTypeObject.view);
        } else {
            tempOverideParams.addErrorView(codeTypeObject.view);
        }
        activity.filterRootView_errorView.put(filter.hashCode()+filter.getClass().getName(), tempOverideParams);
    }

    public void refresh(final BaseRequestFilterLayer filter) {
        View button = codeTypeObject.view.findViewById(codeTypeObject.buttonId);
        if (button == null) {
            LogcatHelper.showError("在ProcessCodeType中看下错误页面的button id 是不是写错了");
        } else {
            button.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    filter.errorRefresh();
                }
            });
        }

    }

    public String[] getIdChar() {
        int ol_overideLayout = activity.getResources().getIdentifier("ol_overideLayout", "id", activity.getPackageName());
        if (ol_overideLayout == 0) {//如果当前布局中没有注册这个控件，那么直接返回
            return null;
        }

        OverideLayout overideLayout = (OverideLayout) rootView.findViewById(ol_overideLayout);
        OverideLayout.IdMap idMap = overideLayout.idHashMap.get(codeTypeObject.codeType);
        if (idMap == null) {
            return null;
        }

        String top = idMap.startId;//
        String bottom = idMap.endId;//

        String[] idChar = new String[2];
        idChar[0] = top;
        idChar[1] = bottom;
        return idChar;
    }

    public int[] getLocationOnScreen(int viewId) {
        View view = rootView.findViewById(viewId);
        if (view == null) {
            return null;
        }
        //获取View在手机屏幕中的位置
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        return location;
    }

}	